/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.userorder.web;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.alipay.api.domain.TransOrderDetail;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.userorder.entity.UserOrder;
import com.jeeplus.modules.userorder.service.UserOrderService;

/**
 * 用户订单Controller
 * @author zhych
 * @version 2021-08-23
 */
@RestController
@RequestMapping(value = "/userorder/userOrder")
public class UserOrderController extends BaseController {

	@Autowired
	private UserOrderService userOrderService;

	@ModelAttribute
	public UserOrder get(@RequestParam(required=false) String id) {
		UserOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = userOrderService.get(id);
		}
		if (entity == null){
			entity = new UserOrder();
		}
		return entity;
	}

//	/**
//	 * 订单数据统计
//	 * @return 统计数据
//	 */
//	@RequestMapping("countData")
//	public AjaxJson countData() {
//		Map<String, Object> map = new HashMap<>();
//		// 查询今日收款
//		String today = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4') and TO_DAYS(create_date) = TO_DAYS(NOW())").toString();
//		map.put("today", new BigDecimal(today).setScale(2, BigDecimal.ROUND_HALF_UP));
//		// 查询累计收款
//		String sum = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('2', '3', '4')").toString();
//		map.put("sum", new BigDecimal(sum).setScale(2, BigDecimal.ROUND_HALF_UP));
//		// 查询累计实收
//		String income = userOrderService.executeGetSql("SELECT ifnull(SUM(income), 0) FROM t_user_order WHERE order_state in ('2', '3', '4')").toString();
//		map.put("income", new BigDecimal(income).setScale(2, BigDecimal.ROUND_HALF_UP));
//		// 查询累计返佣
//		String brokerage = userOrderService.executeGetSql("SELECT ifnull(SUM(brokerage), 0) FROM t_user_order WHERE order_state in ('2', '3', '4')").toString();
//		map.put("brokerage", new BigDecimal(brokerage).setScale(2, BigDecimal.ROUND_HALF_UP));
//		return AjaxJson.success().put("countData", map);
//	}

//	/**
//	 * 订单数据统计
//	 * @return 统计数据
//	 */
//	@RequestMapping("money")
//	public AjaxJson money() {
//		String today = userOrderService.executeGetSql("SELECT ifnull(SUM(pay_amount), 0) FROM t_user_order WHERE order_state in ('6')").toString();
//		return AjaxJson.success().put("money", new BigDecimal(today).setScale(2, BigDecimal.ROUND_HALF_UP));
//	}

	/**
	 * 用户订单列表数据
	 */
	@RequiresPermissions("userorder:userOrder:list")
	@GetMapping("list")
	public AjaxJson list(UserOrder userOrder, HttpServletRequest request, HttpServletResponse response) {
		Page<UserOrder> pa = new Page<>();
		pa.setOrderBy(" a.create_date desc");
		pa.setPageNo(Integer.parseInt(request.getParameter("pageNo")));
		pa.setPageSize(Integer.parseInt(request.getParameter("pageSize")));
		Page<UserOrder> page = userOrderService.findPage(pa, userOrder);
		// 查询订单统计数据
		Page<UserOrder> pa1 = new Page<>();
		pa1.setOrderBy(" a.create_date desc");
		userOrder.setPage(pa1);
		List<UserOrder> list = userOrderService.findList(userOrder);
		// 查询今日收款
		BigDecimal today = BigDecimal.ZERO;
		// 查询累计收款
		BigDecimal sum = BigDecimal.ZERO;
		// 查询累计实收
		BigDecimal income = BigDecimal.ZERO;
		// 查询累计返佣
		BigDecimal brokerage = BigDecimal.ZERO;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		for (UserOrder order : list) {
			// 今日收款
			if (StringUtils.isNotBlank(order.getPayAmount()) && sdf.format(order.getCreateDate()).compareTo(sdf.format(new Date())) == 0 && ("234".contains(order.getOrderState()))) {
				today = today.add(new BigDecimal(order.getPayAmount()));
			}
			// 累计收款
			if (StringUtils.isNotBlank(order.getPayAmount()) && ("234".contains(order.getOrderState()))) {
				sum = sum.add(new BigDecimal(order.getPayAmount()));
			}
			// 实收
			if (StringUtils.isNotBlank(order.getIncome()) && ("234".contains(order.getOrderState()))) {
				income = income.add(new BigDecimal(order.getIncome()));
			}
			// 查询累计返佣
			if (StringUtils.isNotBlank(order.getBrokerage()) && ("234".contains(order.getOrderState()))) {
				brokerage = brokerage.add(new BigDecimal(order.getBrokerage()));
			}
		}
		return AjaxJson.success().put("page",page).put("today", today.setScale(2, BigDecimal.ROUND_HALF_UP)).put("sum", sum.setScale(2, BigDecimal.ROUND_HALF_UP)).put("income", income.setScale(2, BigDecimal.ROUND_HALF_UP)).put("brokerage", brokerage.setScale(2, BigDecimal.ROUND_HALF_UP));
	}

	/**
	 * 根据Id获取用户订单数据
	 */
	@RequiresPermissions(value={"userorder:userOrder:view","userorder:userOrder:add","userorder:userOrder:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(UserOrder userOrder) {
		return AjaxJson.success().put("userOrder", userOrder);
	}

	/**
	 * 保存用户订单
	 */
	@RequiresPermissions(value={"userorder:userOrder:add","userorder:userOrder:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(UserOrder userOrder, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(userOrder);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		userOrderService.save(userOrder);//保存
		return AjaxJson.success("保存用户订单成功");
	}


	/**
	 * 批量删除用户订单
	 */
	@RequiresPermissions("userorder:userOrder:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			userOrderService.deleteByLogic(new UserOrder(id));
		}
		return AjaxJson.success("删除用户订单成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("userorder:userOrder:export")
    @GetMapping("export")
    public AjaxJson exportFile(UserOrder userOrder, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "用户订单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<UserOrder> page = userOrderService.findPage(new Page<UserOrder>(request, response, -1), userOrder);
    		new ExportExcel("用户订单", UserOrder.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出用户订单记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("userorder:userOrder:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<UserOrder> list = ei.getDataList(UserOrder.class);
			for (UserOrder userOrder : list){
				try{
					userOrderService.save(userOrder);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条用户订单记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条用户订单记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入用户订单失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入用户订单数据模板
	 */
	@RequiresPermissions("userorder:userOrder:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "用户订单数据导入模板.xlsx";
    		List<UserOrder> list = Lists.newArrayList();
    		new ExportExcel("用户订单数据", UserOrder.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }

    @RequestMapping("refund")
	public AjaxJson refund(String id) {
		UserOrder userOrder = userOrderService.get(id);
		userOrderService.refund(userOrder, appId, mchNo, mchSecret, certPath);
		return AjaxJson.success("退款成功");
	}
}